import {
    StyleSheet,
    Text,
    View,
    Image,
    Pressable,
    TextInput,
    Modal,
    ScrollView,
    PermissionsAndroid,
    AppState,
    Linking,
} from 'react-native';
import React, { useState, useEffect, useRef } from 'react';
import { useNavigation, useNavigationState, useRoute } from '@react-navigation/native';
import WifiManager from 'react-native-wifi-reborn';
import { useTranslation } from 'react-i18next';
import Icon from 'react-native-vector-icons/Ionicons';
import { yjhDevices } from '~/utils/deviceMenues';
import { NavBarHeader, MyLoading } from '~/components';
import { isIos, onePx, px2dp, scale, width } from '~/utils/px2dp';
import { deviceStore, observer } from '~/store';
import { useTimeout } from '~/common';
import { setWIFINetWork } from '~/utils/ble/application';
import { openLocationSettings } from '~/utils/permission';

export default observer(() => {
    const { t } = useTranslation();
    const router: any = useRoute();
    const { actionType = 'normal' } = router.params || {};
    const loadingRef = useRef<any>();
    const navigation: any = useNavigation();
    const [wifiData, setWifiData] = useState<any>([]);
    const [visible, setVisible] = useState(false);
    const [wifiName, setWifiName] = useState('');
    const [pwd, setPwd] = useState('');
    const [isTimeout, startTimer, resetTimer] = useTimeout(20); // 获取超时相关

    // 获取当前连接的wifi信息
    const getSSID = () => {
        WifiManager.getCurrentWifiSSID()
            .then((res) => {
                setWifiName(res);
            })
            .catch((err) => {
                setWifiName('');
            });
    };

    // 获取wifi列表
    const wifiList = async () => {
        await WifiManager.loadWifiList()
            .then((res) => {
                setWifiData(res);
            })
            .catch((err) => {
                Toast.show({ content: t('wifi.t17'), layout: 'top' });
            });
    };

    // android 检测wifi列表
    const openWifi = async () => {
        if (isIos()) {
            Linking.openURL('App-Prefs:root=WIFI');
        } else {
            const enabled = await WifiManager.isEnabled();
            if (enabled) {
                setVisible(!visible);
                wifiList();
            } else {
                Toast.show({ content: t('wifi.t1'), layout: 'top' });
            }
        }
    };

    const slectWifi = (row) => {
        setWifiName(row.SSID);
        setVisible(false);
    };
    // 开始配网
    const ToUTF8 = (str) => {
        var result = new Array();
        var k = 0;
        for (var i = 0; i < str.length; i++) {
            var j = encodeURI(str[i]);
            if (j.length == 1) {
                // 未转换的字符
                result[k++] = j.charCodeAt(0);
            } else {
                // 转换成%XX形式的字符
                var bytes = j.split('%');
                for (var l = 1; l < bytes.length; l++) {
                    result[k++] = parseInt('0x' + bytes[l]);
                }
            }
        }
        return result;
    };
    const str = ToUTF8(wifiName + pwd);
    const name = ToUTF8(wifiName);
    const pwdLenth = ToUTF8(pwd);
    var sendArray: any = [];
    sendArray = sendArray.concat(name.length, pwdLenth.length, str);
    const startWifi = async () => {
        if (!wifiName) {
            Toast.show({ content: t('wifi.t2'), layout: 'top' });
            return;
        }
        if (!pwd) {
            Toast.show({ content: t('wifi.t3'), layout: 'top' });
            return;
        }
        if (deviceStore.device.connectedDeviceStatus !== 1) {
            Toast.show({ content: t('wifi.t4'), layout: 'top' });
            return;
        }
        loadingRef.current.showLoading();
        setWIFINetWork(sendArray);
        startTimer();
    };

    const checkLoactionPermission = async () => {
        if (isIos()) {
            getSSID();
            return;
        }
        const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, {
            title: t('wifi.t18'),
            message: t('wifi.t19'),
            buttonNegative: t('wifi.t20'),
            buttonPositive: t('wifi.t21'),
        });
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            getSSID();
            wifiList();
        } else {
            Toast.show({ content: t('wifi.t17'), layout: 'top' });
            openLocationSettings();
        }
    };

    const handleAppStateChange = (nextAppState: any) => {
        if (nextAppState != null && nextAppState === 'active') {
            if (isIos()) {
                getSSID();
            } else {
                getSSID();
                wifiList();
            }
        } else if (nextAppState != null && nextAppState === 'background') {
        }
    };

    useEffect(() => {
        AppState.addEventListener('change', handleAppStateChange); // ios隐私跟踪权限获取
        checkLoactionPermission();
        return () => {
            if (actionType == 'network') {
                return;
            }
            deviceStore.disConnectble();
        };
    }, []);

    useEffect(() => {
        if (isTimeout) {
            Toast.show({ content: t('wifi.t5'), layout: 'top' });
            loadingRef.current.hideLoading();
            resetTimer();
        }
    }, [isTimeout]);
    const routes = useNavigationState((state) => state.routes);
    const index = useNavigationState((state) => state.index);
    const previousRoute: any = routes[index - 1];
    useEffect(() => {
        if (deviceStore.successWifi == -1) return;
        if (deviceStore.successWifi == 0) {
            loadingRef.current.hideLoading();
            resetTimer();
            if (deviceStore.device.connectDevice.device_code == 'YY08') {
                if (actionType == 'network') {
                    navigation.goBack();
                    return;
                }
                Toast.show({ content: t('wifi.t23') });
                setTimeout(() => {
                    navigation.navigate('AiActivation');
                }, 1000);
            } else {
                if (previousRoute.name == 'ScanDeviceResult') {
                    navigation.navigate('Main');
                } else {
                    navigation.goBack();
                }
            }
        } else {
            Toast.show({ content: t('wifi.t6'), layout: 'top' });
            loadingRef.current.hideLoading();
            resetTimer();
        }
    }, [deviceStore.successWifi, deviceStore.device.connectDevice.device_code]);

    return (
        <View style={styles.container}>
            <NavBarHeader title={t('wifi.title')} />
            <View style={styles.content}>
                <Text style={styles.title}>{t('wifi.t7')}</Text>
                <View style={[styles.flex, styles.line]}>
                    <View style={styles.flex}>
                        <Image source={require('~/assets/deviceTools/icon_wifi.png')} style={styles.icons} />
                        <Text style={styles.leftTitle}>{wifiName}</Text>
                    </View>

                    <Pressable onPress={openWifi}>
                        <Icon name="chevron-down-outline" size={22} color="#a4a4a4"></Icon>
                    </Pressable>
                </View>
                <View style={[styles.tip, styles.flex]}>
                    <Icon name="star" size={10} color="#FF4E4E"></Icon>
                    <Text style={styles.tips}>{t('wifi.t8')}</Text>
                </View>
                {isIos() && (
                    <View style={[styles.tip, styles.flex]}>
                        <Icon name="star" size={10} color="#FF4E4E"></Icon>
                        <Text style={styles.tips}>{t('wifi.t22')}</Text>
                    </View>
                )}
                <View style={[styles.flex, styles.line]}>
                    <View style={styles.flex}>
                        <Image source={require('~/assets/deviceTools/icon_pdw.png')} style={styles.icons} />
                        <View style={{ marginLeft: px2dp(32) }}>
                            <TextInput
                                placeholder={t('wifi.t9')}
                                style={{ color: '#000', fontSize: scale(30) }}
                                placeholderTextColor={'#a4a4a4'}
                                value={pwd}
                                onChangeText={(val) => {
                                    setPwd(val);
                                }}
                            />
                        </View>
                    </View>
                </View>

                <View style={[styles.tip, styles.flex]}>
                    <Icon name="star" size={10} color="#FF4E4E"></Icon>
                    <Text style={styles.tips}>{t('wifi.t10')}</Text>
                </View>
                <Pressable style={styles.bootom_button} onPress={() => startWifi()}>
                    <Text style={styles.bootom_buttonText}>{t('wifi.t11')}</Text>
                </Pressable>
            </View>
            <Modal visible={visible} transparent={true} statusBarTranslucent={true} hardwareAccelerated={true}>
                <View style={styles.modalContainer}>
                    <View style={styles.modalContent}>
                        <View style={[styles.flex, styles.modal_header]}>
                            <View />
                            <Text>{t('wifi.t12')}</Text>
                            <Pressable onPress={() => setVisible(false)}>
                                <Icon name="close" size={22} color="#a4a4a4"></Icon>
                            </Pressable>
                        </View>
                        <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ flexGrow: 1 }}>
                            {wifiData.map((item, index) => {
                                if (item.frequency >= 3000) return;
                                return (
                                    <Pressable
                                        key={index}
                                        style={[styles.flex, styles.list]}
                                        onPress={() => {
                                            slectWifi(item);
                                        }}>
                                        <Text>{item?.SSID}</Text>
                                        <Text>{(item.frequency / 1000)?.toFixed(1)}G</Text>
                                    </Pressable>
                                );
                            })}
                        </ScrollView>
                    </View>
                </View>
            </Modal>
            <MyLoading ref={loadingRef} title={t('wifi.t13')} />
        </View>
    );
});

const styles = StyleSheet.create({
    flex: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    content: {
        flex: 1,
        marginHorizontal: px2dp(32),
        marginTop: px2dp(20),
    },
    title: {
        color: '#191919',
        fontWeight: 'bold',
        fontSize: scale(34),
    },
    icons: {
        width: px2dp(40),
        height: px2dp(40),
    },
    line: {
        borderBottomWidth: onePx,
        borderBottomColor: '#eee',
        justifyContent: 'space-between',
        marginTop: px2dp(60),
        paddingBottom: px2dp(10),
    },
    leftTitle: {
        marginLeft: px2dp(32),
        fontSize: scale(32),
        color: '#191919',
    },
    tip: {
        marginVertical: px2dp(20),
    },
    tips: {
        color: '#000',
        fontSize: px2dp(28),
        marginLeft: px2dp(20),
    },
    bootom_button: {
        backgroundColor: '#1877FF',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(16),
        height: px2dp(100),
        marginTop: '40%',
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    modalContainer: {
        width: width - 24,
        alignSelf: 'center',
        position: 'absolute',
        top: '26%',
    },
    modalContent: {
        backgroundColor: '#fff',
        borderWidth: onePx,
        borderColor: '#a8a8a8',
        height: '50%',
        width: width - 24,
        borderRadius: 10,
        padding: px2dp(24),
    },
    list: {
        justifyContent: 'space-between',
        borderBottomWidth: onePx,
        borderColor: '#eee',
        paddingBottom: px2dp(20),
        marginTop: px2dp(16),
    },
    modal_header: {
        justifyContent: 'space-between',
        borderBottomWidth: onePx,
        borderColor: '#eee',
        marginBottom: px2dp(34),
        paddingBottom: px2dp(10),
    },
});
